package com.net.xpay.common.service.impl;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.common.domain.CheckCode;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.enums.user.CheckCodeType;
import com.net.xpay.common.manager.CheckCodeManager;
import com.net.xpay.common.model.DevelopSettingsModel;
import com.net.xpay.common.util.JWTUtil;
import com.net.xpay.common.validator.CheckCodeValidator;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.constant.WebConstant;
import com.net.common.exception.BusinessException;
import com.net.xpay.common.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserProfileServiceImpl implements UserProfileService {

    @Autowired
    private CheckCodeManager checkCodeManager;

    @Autowired
    private CheckCodeValidator checkCodeValidator;

    @Override
    public String getDevelopSettingsToken(User user, DevelopSettingsModel model) {
        if (Strings.isNullOrEmpty(model.getCheckCode())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "验证码不能为空");
        }
        //验证验证码
        CheckCode checkCode = checkCodeManager.findByMobileAndType(user.getMobile(), CheckCodeType.DEVELOP_SETTINGS);
        checkCodeValidator.validateCheckCode(checkCode, model.getCheckCode());

        return getToken(user.getId());

    }


    private String getToken(Long userId) {
        Preconditions.checkArgument(userId != null);
        //授权
        Map<String, String> payload = new HashMap<>();
        payload.put(WebConstant.DEV_TOKEN_PAYLOAD_KEY, userId.toString());

        return JWTUtil.getToken(WebConstant.DEV_TOKEN_EXPIRED_SECONDS, payload);
    }

}
